import React, { Component } from 'react';
import { Form } from 'antd';

import PropTypes from 'prop-types'


class FormLay extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    onFinish = (values) => {
        this.props.onSearch(values);
    };
    onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    render() {

        let { fromConfig, children, style, formLayout, initial, name, form, labelAlign } = this.props;
        return (
            <>
                <Form
                    name={name}
                    form={form}
                    initialValues={initial}
                    style={style}
                    layout={formLayout}
                    onFinish={this.onFinish}
                    onFinishFailed={this.onFinishFailed}
                    labelCol={{ span: 6 }}
                >
                    {
                        fromConfig.map((item, index) => {
                            return (
                                <Form.Item
                                    label={item.label}
                                    name={item.name}
                                    key={index}
                                    rules={item.rules}
                                    labelAlign={labelAlign}
                                >
                                    {/* 动态创建 */}
                                    {typeof item.ele === 'function' ? item.ele(initial, item.name) : React.createElement(item.ele, {
                                        placeholder: item.placeholder,
                                    })}
                                </Form.Item>
                            )
                        })
                    }
                    {/* 判断children是否存在 */}
                    {children && <Form.Item>{children}</Form.Item>}
                </Form>
            </>
        );
    }
}

FormLay.propTypes = {
    fromConfig: PropTypes.array.isRequired,//根据该配置动态生成表单
    style: PropTypes.object,
    formLayout: PropTypes.oneOf(['horizontal', 'vertical', 'inline']),
    initial: PropTypes.object.isRequired,
    onSearch: PropTypes.func,
    name: PropTypes.string,
    form: PropTypes.object,
    labelAlign: PropTypes.oneOf(['left', 'right'])
}
FormLay.defaultProps = {
    formLayout: "horizontal",
    labelAlign: "right"
}

export default FormLay;